package orm

import (
	error2 "gitee.com/xiawucha365/sago.v2/core/error"
	"gitee.com/xiawucha365/sago.v2/core/util"
	"github.com/jinzhu/gorm"
)

func (dbm *Db) FindBySql(sql string, out interface{}) error {

	if dbm.engineType == DbMysqlEngineTypeXorm {
		res, err := dbm.Engine.Xorm.QueryString(sql)
		if err != nil {
			return err
		} else {
			if res1, err := util.JsonEncode(res); err != nil {
				//panic("json error")
				return err
			} else {
				_ = util.JsonDecode(res1, out)
			}
		}
	} else {
		db := dbm.Engine.Gorm.Raw(sql).Find(out)
		return db.Error
	}
	return nil

}

func (dbm *Db) GetById(id int, out interface{}) error {
	if dbm.engineType == DbMysqlEngineTypeXorm {
		has, err := dbm.Engine.Xorm.ID(id).Get(out)
		if err != nil {
			return err
		} else {
			if !has {
				return error2.ErrRecordNotFound
			}
		}
	} else {
		db := dbm.Engine.Gorm.First(out, id)
		if db.Error == gorm.ErrRecordNotFound {
			return error2.ErrRecordNotFound
		}
	}
	return nil
}

func (dbm *Db) Get(query interface{}, out interface{}) error {
	if dbm.engineType == DbMysqlEngineTypeXorm {
		has, err := dbm.Engine.Xorm.Where(query).Get(out)
		if err != nil {
			return err
		} else {
			if !has {
				return error2.ErrRecordNotFound
			}
		}
	} else {
		db := dbm.Engine.Gorm.Where(query).First(out)
		if db.Error == gorm.ErrRecordNotFound {
			return error2.ErrRecordNotFound
		}
	}
	return nil
}

func (dbm *Db) Insert(bean interface{}) error {
	if dbm.engineType == DbMysqlEngineTypeXorm {
		_, err := dbm.Engine.Xorm.Insert(bean)
		if err != nil {
			return err
		}
	} else {
		db := dbm.Engine.Gorm.Create(bean)
		if db.Error != nil {
			return error2.ErrInsertFail
		}
	}
	return nil
}

func (dbm *Db) UpdateById(id int, bean interface{}) error {
	if dbm.engineType == DbMysqlEngineTypeXorm {
		_, err := dbm.Engine.Xorm.Id(id).Update(bean)
		if err != nil {
			return err
		}
	} else {
		//待完善
		//db := dbm.Engine.Gorm.Model(bean).Updates(bean)
		//if db.Error != nil {
		return error2.ErrUpdateFail
		//}
	}
	return nil
}
